package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"github.com/google/uuid"
	"good/good"
	"order/order"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderCreateLogic) OrderCreate(req *types.OrderCreaterequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	s := l.ctx.Value("userId").(string)
	atoi, err := strconv.Atoi(s)
	if err != nil {
		return nil, err
	}
	show, err := l.svcCtx.GoodRpc.GoodShow(l.ctx, &good.GoodShowRequest{Id: req.GoodId})
	if err != nil {
		return &types.Response{
			Message: "服务器错误",
			Code:    "-1",
			Data:    nil,
		}, nil
	}
	if show.GoodShow.Id == 0 { //判断商品是否存在
		return &types.Response{
			Message: "商品已下架",
			Code:    "-2",
			Data:    nil,
		}, nil
	}
	if show.LenShopStock < req.GoodNum { //判断商品库存是否充足
		return &types.Response{
			Message: "库存不足",
			Code:    "-3",
			Data:    nil,
		}, nil
	}

	amount := show.GoodShow.GoodPrice * req.GoodNum //计算商品总金额
	create, err := l.svcCtx.OrderRpc.OrderCreate(l.ctx, &order.OrderCreateRequest{
		GoodId:  req.GoodId,
		GoodNum: req.GoodNum,
		Amount:  amount,
		OrderSn: uuid.NewString(),
		PayType: int64(req.PayType),
	})
	if err != nil {
		return &types.Response{
			Message: "订单添加失败",
			Code:    "-4",
			Data:    nil,
		}, nil
	}
	goodCreate, err := l.svcCtx.OrderRpc.OrderGoodCreate(l.ctx, &order.OrderGoodCreateRequest{
		GoodTitle:  show.GoodShow.GoodTitle,
		GoodPrice:  show.GoodShow.GoodPrice,
		GoodStock:  show.GoodShow.GoodStock,
		GoodCover:  show.GoodShow.GoodCover,
		GoodStatus: show.GoodShow.GoodStatus,
		UserId:     int64(atoi),
		OrderId:    create.Id,
	})
	if err != nil {
		return &types.Response{
			Message: "订单生成失败",
			Code:    "-5",
			Data:    nil,
		}, nil
	}
	_, err = l.svcCtx.OrderRpc.DeleteGood(l.ctx, &order.DeleteGoodRequest{
		Id:      req.GoodId,
		GoodNum: req.GoodNum,
	})
	if err != nil {
		return &types.Response{
			Message: "订单生成失败",
			Code:    "-6",
			Data:    nil,
		}, nil
	}
	pay := pkg.ALiPay("支付宝支付", uuid.NewString(), fmt.Sprintf("%v", amount)) //调用支付宝支付
	return &types.Response{
		Message: "订单生成成功",
		Code:    "200",
		Data: map[string]interface{}{
			"goodCreate": goodCreate,
			"pay":        pay,
		},
	}, nil
}
